$Import('app.common.menuEvent');

STK.register('app.actui.downmenu',function($){
	/*
	 * spec = {
			region : 
			tag : 
			over :
			delay :
		}
	 */
	return function(spec){
		var region = spec.region;
		var defaultValue = spec.defaultValue;
		var values = spec.values;
		var onchange = spec.onchange;
		var nodetype = spec.nodetype;
		var MENUTEMPLATE = '<a node-type="header" class="select" href="javascript:void(0);"><em><span node-type="value" value="#{defaultValue}">#{defaultName}</span>▼</em></a><div node-type="body" class="option">#{items}</div>';
		var ITEMTEMPLATE = '<p><a href="javascript:void(0)" value="#{value}">#{name}</a></p>';
		var html ="";
		var defaultName = "";
		for (i in values) {
			var item = values[i];
			if(item.value == defaultValue){
				defaultName  =item.name;
			}
			html += $.templet(ITEMTEMPLATE, item);
		}
		MENUTEMPLATE = $.templet(MENUTEMPLATE,{defaultValue:defaultValue,defaultName:defaultName,items:html});
		var dom = $.builder(MENUTEMPLATE), header = dom.list['header'][0],body = dom.list['body'][0],value = dom.list['value'][0];
		region.appendChild(header);
		region.appendChild(body);
		var change = function(val,name){
			if(val == value.getAttribute("value")){
				return;
			}
			if(!name){
				name = $.sizzle('a[value="'+val+'"]', body)[0].innerHTML;
			}
			value.innerHTML = name;
			value.setAttribute("value",val);
			onchange && onchange(val);
		};
		
		$.addEvent(body, 'click', function(e){
			var e = $.fixEvent(e), el = e.target, val = el.getAttribute("value");
			region.className = "";
			change(val,el.innerHTML);
		});
		
		var menu = $.app.common.menuEvent({
			region:region,
			tag:'DIV',
			nodetype:nodetype,
			over:function(el){el.className = "current";}
		});
		
		var that = {};
		that.destroy = function() {
			menu.destroy();
		};
		that.change = change;
		return that;
	};
});